package com.enfo.zjabank.filter;

import com.enfo.zjabank.dao.SessionDao;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by zhoum on 2016/8/22.
 */
public class SessionFilter implements Filter{
    private Logger logger = LoggerFactory.getLogger(SessionFilter.class);
//    @Resource
    private SessionDao sessionDao;
    String pyUrl = null;
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response1;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(filterConfig.getServletContext());
        this.sessionDao = ctx.getBean(SessionDao.class);
        Properties p = new Properties();
        try {
            p.load(SessionFilter.class.getClassLoader().getResourceAsStream("upload.properties"));
            pyUrl = p.getProperty("pyUrl");
            logger.info("配置文件中读取到python项目地址为:"+pyUrl);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("读取数据库配置文件失败！");
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Cookie[] cookies = ((HttpServletRequest)request).getCookies();
//        cookiesAndRequest(cookies,request);
        HttpSession session = ((HttpServletRequest) request).getSession();

        if(cookies != null){
            boolean flag = false;
            for(Cookie c :cookies ){
//                logger.debug(c.getName() + "--->" + c.getValue());
//                if("login_user".equals(c.getName())){
//                    request.setAttribute("inputUser",c.getValue());
//                }
                Object aa = session.getAttribute("inputUser");
                if("webpy_session_id".equals(c.getName()) && sessionDao.checkSessionExist(c.getValue())){
                    if(aa==null){
                        HttpGet httpGet = new HttpGet("http://"+pyUrl+"/x/zjabank/rst/session?session_id="+c.getValue());
                        try {
                            response1 = httpclient.execute(httpGet);

                            HttpEntity entity1 = response1.getEntity();
                            String inputUser = EntityUtils.toString(entity1);
                            session.setAttribute("inputUser", inputUser);
                            if(logger.isDebugEnabled()){
                                logger.debug("session获取到当前登录人为:"+inputUser);
                            }
                            request.setAttribute("inputUser",inputUser);
                            EntityUtils.consume(entity1);
                        } catch (IOException e) {
                            logger.error("session请求异常",e);
                        }
                    }
                    flag = true;
                }
            }
            if(flag){
                chain.doFilter(request, response);
            }
        }else{
            chain.doFilter(request, response);
        }
        return;
//        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        try {
            response1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void cookiesAndRequest(Cookie[] cookies,ServletRequest request){
        for(Cookie c :cookies ){
            logger.info(c.getName() + "--->" + c.getValue());
        }
        logger.info("========================");
        Map<String,String[]> requestMap = request.getParameterMap();
        for(Map.Entry<String,String[]> entry:requestMap.entrySet()){
            logger.info(entry.getKey()+"--->");
            for(String str:entry.getValue()){
                logger.info(str);
            }
        }
    }
}
